package cn.itcast.dao;

import cn.itcast.model.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class BlogDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    public void insert(Blog blog) {
        mongoTemplate.insert(blog);
    }

    public Blog findByID(String id) {
        return mongoTemplate.findById(id, Blog.class);
    }


    public void deleteByID(String id) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)), Blog.class);
    }

    public List<Blog> find(Blog blog) {
        if (null == blog) {
            return null;
        }
        Criteria criteria = getFilter(blog);
        return mongoTemplate.find(Query.query(criteria), Blog.class);

    }

    public Criteria getFilter(Blog blog) {
        Criteria criteria = new Criteria();
        if (!StringUtils.isEmpty(blog.getTitle())) {
            criteria.andOperator(Criteria.where("title").is(blog.getUrl()));
        }
        if (!StringUtils.isEmpty(blog.getBy())) {
            criteria.andOperator(Criteria.where("by").is(blog.getBy()));
        }
        if (!StringUtils.isEmpty(blog.getLikes())) {
            criteria.andOperator(Criteria.where("likes").is(blog.getLikes()));
        }
        if (null != blog.getTags() && !blog.getTags().isEmpty()) {
            criteria.andOperator(Criteria.where("tags").in(blog.getTags()));
        }
        return criteria;
    }

}